﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Yunwei.BizLogic;
using Yunwei.IBizLogic;
using Yunwei.Web.Areas.Admin.Models;
using Microsoft.AspNet.Identity;
using Yunwei.Domain.Models;

namespace Yunwei.Web.Areas.Admin.Controllers
{
    public class VendorController : Controller
    {
        IVendorService _vendorService;
        IVendorIngredientService _vendorIngredientService;
        IVendorCustomerService _vendorCustomerService;
        IRestaurantService _restaurantService;
        public VendorController()
        {
            _vendorService = new VendorService();
            _vendorIngredientService = new VendorIngredientService();
            _vendorCustomerService = new VendorCustomerService();
            _restaurantService = new RestaurantService();
        }


        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Vendor")]
        public ActionResult Setting()
        {
            if (Request.IsAuthenticated)
            {
                Vendor vendor = _vendorService.FindByUserId(User.Identity.GetUserId<int>());
                
                return View(VendorViewModel.FromVendor(vendor));
            }

            return RedirectToAction("Login", "User", new { Area = "Admin", returnUrl = "~/Admin/Vendor/Setting" });
        }

        [Authorize(Roles="Vendor")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Setting(VendorViewModel vendor)
        {
            if (Request.IsAuthenticated&&ModelState.IsValid)
            {
                Vendor v;
                if (vendor.User_Id <= 0)
                {
                    vendor.User_Id = User.Identity.GetUserId<int>();
                    v = _vendorService.Add(vendor.Vendor);
                }
                else
                {
                    v = vendor.Vendor;
                    _vendorService.Update(v);
                }

                if (v == null || v.Id <= 0)
                {
                    ModelState.AddModelError("", "设置基本信息失败");
                }
                else
                {
                    ModelState.AddModelError("", "设置基本信息成功");
                }
            }

            return View(vendor);
        }

        #region Ingredient
        public ActionResult Ingredient()
        {
            if (Request.IsAuthenticated)
            {
                Vendor vendor = _vendorService.FindByUserId(User.Identity.GetUserId<int>());
                if (vendor == null)
                {
                    return RedirectToAction("Setting");
                }
                var vis = _vendorIngredientService.FindList(10, "", vendor.Id, 0);
                List<VendorIngredientViewModel> vivms = new List<VendorIngredientViewModel>();
                foreach (var vi in vis)
                {
                    VendorIngredientViewModel viv = VendorIngredientViewModel.FromVendorIngredient(vi);
                    vivms.Add(viv);
                }
                return View(vivms);
            }

            return RedirectToAction("Login", "User", new { Area = "Admin", returnUrl = "~/Admin/Vendor/Ingredient" });
        }

        public ActionResult AddIngredient()
        {
            if (Request.IsAuthenticated)
            {
                return View(new VendorIngredientViewModel());
            }

            return RedirectToAction("Login", "User", new { Area = "Admin", returnUrl = "~/Admin/Vendor/AddIngredient" });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult AddIngredient(VendorIngredientViewModel vm)
        {
            if (Request.IsAuthenticated)
            {
                if (ModelState.IsValid)
                {
                    Vendor vendor = _vendorService.FindByUserId(User.Identity.GetUserId<int>());
                    vm.Vendor_Id = vendor.Id;
                    var vi = _vendorIngredientService.Add(vm.VendorIngredient);
                    if (vi != null && vi.Id > 0)
                    {
                        vm.Id = vi.Id;
                        return RedirectToAction("Ingredient");
                    }
                    else
                    {
                        ModelState.AddModelError("", "添加新的食材失败");
                        return View(vm);
                    }
                }
                else
                {
                    return View(vm);
                }
            }

            return RedirectToAction("Login", "User", new { Area = "Admin", returnUrl = "~/Admin/Vendor/AddIngredient" });
        }

        [Authorize]
        public ActionResult EditIngredient(int id)
        {
            var vi = _vendorIngredientService.Find(id);
            if (vi == null)
            {
                return RedirectToAction("Error404", "Home", new { Id = id });
            }

            var vivm = VendorIngredientViewModel.FromVendorIngredient(vi);
            vivm.UnitItems.Find(i => i.Value == vi.Unit).Selected = true;
            return View(vivm);
        }

        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult EditIngredient(VendorIngredientViewModel vivm)
        {
            if (_vendorIngredientService.Update(vivm.VendorIngredient))
            {
                return RedirectToAction("Ingredient");
            }
            else
            {
                ModelState.AddModelError("", "编辑失败");
            }
            return View(vivm);
        }

        [Authorize]
        public ActionResult DeleteIngredient(int id)
        {
            var vi = _vendorIngredientService.Find(id);
            if (_vendorIngredientService.Delete(vi))
            {
                return RedirectToAction("Ingredient");
            }
            else
            {
                return RedirectToAction("Ingredient");
            }
        }
        #endregion

        #region Customer
        [Authorize]
        public ActionResult Customers()
        {
            Vendor vendor = _vendorService.FindByUserId(User.Identity.GetUserId<int>());
            if (vendor == null)
            {
                return RedirectToAction("Setting");
            }

            ViewBag.Id = vendor.Id;
            
            var customers = _vendorCustomerService.FindList(10, vendor.Id, 1);

            List<CustomerViewModel> cvms = new List<CustomerViewModel>();
            foreach(var customer in customers)
            {
                cvms.Add(CustomerViewModel.FromVendorCustomer(customer));
            }
            return View(cvms);
        }

        [Authorize]
        [HttpPost]
        public ActionResult GetCustomer(int rid, int vid)
        {
            var restaurant = _restaurantService.Find(rid);

            var cvms = _vendorCustomerService.FindList(10000, vid, 1);
            var cvm1 = cvms.FirstOrDefault(v => v.Restaurant_Id == rid);
            if (restaurant != null && restaurant.Id > 0)
            {
                CustomerViewModel cvm = new CustomerViewModel()
                {
                    Restaurant_Id = restaurant.Id,
                    Vendor_Id = vid,
                    Vendor_Status = cvm1 == null ? (short)0 : cvm1.Vendor_Status
                };

                return Json(cvm);
            }

            return Json(string.Empty);
        }

        [Authorize]
        [HttpGet]
        public ActionResult AddCustomer(int id)
        {
            ViewBag.Id = id;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult AddCustomer(int vendor_Id, int restaurant_Id)
        {
            _vendorCustomerService.Add(new VendorCustomer()
            {
                Restaurant_Id = restaurant_Id,
                Vendor_Id = vendor_Id,
                Vendor_Status = 1,
                Restaurant_Status = 0
            });
            return RedirectToAction("Customers", "Vendor");
        }

        [Authorize]
        public ActionResult Bind(int id)
        {
            var vendorCustomer = _vendorCustomerService.Find(id);
            vendorCustomer.Restaurant_Status = 1;
            vendorCustomer.Vendor_Status = 1;

            _vendorCustomerService.Update(vendorCustomer);

            return RedirectToAction("Customers");

        }

        [Authorize]
        public ActionResult DeleteCustomer(int id)
        {

            var vi = _vendorCustomerService.Find(id);
            if (_vendorCustomerService.Delete(vi))
            {
                return RedirectToAction("Customer");
            }
            else
            {
                return RedirectToAction("Customer");
            }
        }

        [Authorize]
        public ActionResult Details(int id)
        {
             var restaurant = _restaurantService.Find(id);
             return View(restaurant);
        }

        #endregion
    }
}